// @Author EthanScriptOn
// @Desc
package extend_parser

import (
	"fmt"
	"gitee.com/fatzeng/srf_switch_expansion_package/extend_config"
	"gitee.com/fatzeng/srf_switch_stream_bridge/bridge"
	"gitee.com/fatzeng/srf_switch_stream_bridge/framework/actuator"
	"reflect"
)

type LocalWriteResponseParser struct {
}

func (l *LocalWriteResponseParser) Parse(ctx *actuator.SrfSwitchBridgeActuatorContext, config *bridge.BridgeConfig, response interface{}) (interface{}, error) {
	results, ok := response.([]*extend_config.LocalWriteOperatorResponse)
	if !ok {
		return nil, fmt.Errorf("response is not []*extend_config.LocalWriteOperatorResponse")
	}
	if len(results) <= 0 {
		return nil, fmt.Errorf("results is empty")
	}
	if !config.ResultType.AssignableTo(reflect.TypeOf([]*extend_config.LocalWriteResponse{})) {
		return nil, fmt.Errorf("result type is not []*LocalWriteResponse")
	}

	resValue := reflect.New(config.ResultType)
	instance := resValue.Interface()
	produceResponse := instance.([]*extend_config.LocalWriteResponse)

	for _, result := range results {
		resp := new(extend_config.LocalWriteResponse)
		resp.OriginMsg = result.OriginMsg
		resp.FilePath = result.FilePath
		if result.Err != nil {
			resp.IsOk = false
			resp.ErrMsg = fmt.Sprintf("failed to write file: %v", result.Err)
		} else {
			resp.IsOk = true
		}
		produceResponse = append(produceResponse, resp)
	}

	return produceResponse, nil
}
